package sc.tool.sqlgen.branchinfo;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import sc.tool.sqlgen.branchinfo.DiffUnit.DiffType;
import sc.tool.sqlgen.branchinfo.DiffUnit.Filed;

/**
 *
 * <p>TODO:注释</p>
 * 将导入后的数据和数据库中的数据进行比对并返回比较结果
 * @author Zhang Yun
 * @version $Id: Compare.java, v 0.1 2012-11-3 下午12:13:33 User Exp $
 */
public class Comparator {
    public CompareResult compare(List<BranchInfo> dbDataList, List<BranchInfo> bankDataList) {
        Map<String, BranchInfo> dataMap = convert2Map(dbDataList);
        CompareResult compareResult = new CompareResult();
        compareResult.setBankDataCount(bankDataList.size());
        compareResult.setDbDataCount(dbDataList.size());

        //遍历来自银行的数据
        for (BranchInfo bankData : bankDataList) {
            BranchInfo dbData = dataMap.get(bankData.getBranchId());
            DiffUnit diffUnit = compare(dbData, bankData);
            if (diffUnit.getDiffType() != null) {
                compareResult.addDiffUnit(diffUnit);
            }
        }

        return compareResult;

    }

    private DiffUnit compare(BranchInfo dbData, BranchInfo bankData) {
        DiffUnit diffUnit = new DiffUnit();
        diffUnit.setDbData(dbData);
        diffUnit.setBankData(bankData);
        if (dbData == null) {
            diffUnit.setDiffType(DiffType.NEW);
            return diffUnit;
        }

        compareFiled(diffUnit, Filed.BANKCODE, dbData.getBankCode(), bankData.getBankCode());
        compareFiled(diffUnit, Filed.CITYID, dbData.getCityId(), bankData.getCityId());
        compareFiled(diffUnit, Filed.PROVID, dbData.getProvId(), bankData.getProvId());
        compareFiled(diffUnit, Filed.BRANCHNAME, dbData.getBranchName(), bankData.getBranchName());
        return diffUnit;
    }

    private void compareFiled(DiffUnit diffUnit, Filed filed, String dbValue, String bankValue) {
        if (!dbValue.equalsIgnoreCase(bankValue)) {
            diffUnit.addDiffFiled(filed, dbValue, bankValue);
            diffUnit.setDiffType(DiffType.UPDATE);
        }
    }

    private Map<String, BranchInfo> convert2Map(List<BranchInfo> dataList) {
        Map<String, BranchInfo> dataMap = new HashMap<String, BranchInfo>();
        for (BranchInfo data : dataList) {
            dataMap.put(data.getBranchId(), data);
        }
        return dataMap;
    }

}
